package com.loubobooo.personal.blog.controller.backend;

import com.loubobooo.personal.blog.common.Const;
import com.loubobooo.personal.blog.common.ServerResponse;
import com.loubobooo.personal.blog.entity.User;
import com.loubobooo.personal.blog.entity.vo.*;
import com.loubobooo.personal.blog.service.ArticleService;
import com.loubobooo.personal.blog.service.CommentService;
import com.loubobooo.personal.blog.service.UserService;
import com.loubobooo.personal.blog.util.*;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller public class AdminController {
    @Autowired private UserService userService;

    @Autowired private ArticleService articleService;

    @Autowired private CommentService commentService;

    /**
     * @Description: 生成验证码
     * @return     返回类型
     * @date 2018/3/15 15:24
     */
    @RequestMapping(value = "/createCode")
    public void createCode(HttpServletRequest request, HttpServletResponse response){
        // 通知浏览器不要缓存
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        CaptchaUtil captcha = CaptchaUtil.getInstance();
        // 将验证码输入到session中，用来验证
        String verifyCode = captcha.getString();
        request.getSession().setAttribute("verifyCode", verifyCode);
        // 输出打web页面
        try {
            ImageIO.write(captcha.getImage(), "jpg", response.getOutputStream());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    //后台首页
    @RequestMapping("/admin") public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        //文章列表,先去查缓存
        List<ArticleListVo> articleVOList = null;
        String cacheValue = RedisPoolUtil.get(Const.REDIS_KEY.ALL_ARTICLE);
        if(StringUtils.isBlank(cacheValue)){
            articleVOList = articleService.listArticle(null);
            RedisPoolUtil.set(Const.REDIS_KEY.ALL_ARTICLE, JsonUtil.obj2String(articleVOList));
        }else{
            articleVOList = JsonUtil.string2Obj(cacheValue, new TypeReference<List<ArticleListVo>>(){});
        }
        modelAndView.addObject("articleVOList", articleVOList);
        //评论列表
        List<CommentListVo> commentListVoList = commentService.listCommentVo(null);
        modelAndView.addObject("commentListVoList", commentListVoList);
        //评论数
        Integer allCommentCount = commentService.countComment(null);
        Integer approvedCommentCount = commentService.countComment(1);
        Integer hiddenCommentCount = commentService.countComment(0);
        modelAndView.addObject("allCommentCount", allCommentCount);
        modelAndView.addObject("approvedCommentCount", approvedCommentCount);
        modelAndView.addObject("hiddenCommentCount", hiddenCommentCount);

        modelAndView.setViewName("/Admin/index");
        return modelAndView;
    }

    //登录页面显示
    @RequestMapping("/login") public ModelAndView loginView() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/Admin/login");
        return modelAndView;
    }

    //登录验证
    @RequestMapping(value = "/loginVerify", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse loginVerify(
            HttpServletRequest request, HttpServletResponse response) {
        String msg = "";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        String rememberme = request.getParameter("rememberme");

        HttpSession session = request.getSession();
        String code = request.getParameter("code");// 验证码
        String verifyCode = (String) session.getAttribute("verifyCode");

        // 验证码校验
        if (StringUtils.isBlank(verifyCode)) {
            msg = "验证码已过期，请刷新!";
            return ServerResponse.createByErrorMessage(msg);
        }
        if (!StringUtils.equals(verifyCode, code.toUpperCase())) {
            msg = "验证码不正确!";
            return ServerResponse.createByErrorMessage(msg);
        }
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userService.login(username,md5Password);
        if (user == null) {
            msg = "用户名或密码错误!";
        }else {
            //添加session
            request.getSession().setAttribute("user", user);
            //添加cookie
/*            if (rememberme != null) {
                //创建两个Cookie对象
                Cookie nameCookie = new Cookie("username", username);
                //设置Cookie的有效期为3天
                nameCookie.setMaxAge(60 * 60 * 24 * 3);
                Cookie pwdCookie = new Cookie("password", password);
                pwdCookie.setMaxAge(60 * 60 * 24 * 3);
                response.addCookie(nameCookie);
                response.addCookie(pwdCookie);
            }*/
            user.setUserLastLoginTime(new Date());
            user.setUserLastLoginIp(IpUtil.getRemoteIp(request));
            userService.updateUser(user);
            //登录成功
            return ServerResponse.createBySuccess("登录成功！");
        }
        return ServerResponse.createByErrorMessage(msg);
    }

    //退出登录
    @RequestMapping(value = "/admin/logout") public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/login";
    }

}
